package com.csun.cmny.provider.manager;

import com.csun.cmny.provider.model.domain.UacMerchant;
import com.csun.cmny.provider.service.UacMerchantService;
import com.csun.cmny.provider.utils.OnOffTimeUtil;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.RedisKeyUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class MerchantManager {
    @Resource
    private UacMerchantService merchantService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    public final static long ONE_Minute = 1000*60;

    //商家上下线的定时任务
    @Scheduled(fixedDelay=ONE_Minute)
    public void fixedDelayJob(){


        List<UacMerchant> select = merchantService.selectAll();


        for (UacMerchant merchant : select) {

            if (PublicUtil.isNotEmpty(merchant.getOnTime())&&PublicUtil.isNotEmpty(merchant.getOffTime())){

                if(merchant.getIsManual().equals(0)){

                    if(OnOffTimeUtil.isBusiness(merchant.getOnTime(),merchant.getOffTime())){
                        if (merchant.getIsBusiness().equals(0)){
                            merchant.setIsBusiness(1);
                            merchantService.update(merchant);
                        }
                        UacMerchant o = (UacMerchant) redisTemplate.opsForValue().get(RedisKeyUtil.getUacMerchant(merchant.getId().toString()));
                        if (PublicUtil.isNotEmpty(o) && o.getIsBusiness().equals(0)){
                            merchant.setIsBusiness(1);
                            redisTemplate.opsForValue().set(RedisKeyUtil.getUacMerchant(merchant.getId().toString()),merchant);
                        }
                    }
                }
                if (merchant.getIsBusiness().equals(1)&&merchant.getIsManual().equals(0)){
                    if(!OnOffTimeUtil.isBusiness(merchant.getOnTime(),merchant.getOffTime())){
                        merchant.setIsBusiness(0);
                        redisTemplate.opsForValue().set(RedisKeyUtil.getUacMerchant(merchant.getId().toString()),merchant);
                        merchantService.update(merchant);
                    }
                }
            }
        }

    }

    //每天凌晨两点把商家信息写入redis
    @Scheduled(cron = "0 0 2 * * ?")
    public void selectMerchant() {

        List<UacMerchant> uacMerchants = merchantService.selectAll();

        for (UacMerchant uacMerchant : uacMerchants) {
            redisTemplate.opsForValue().set(RedisKeyUtil.getUacMerchant(uacMerchant.getId().toString()),uacMerchant);

        }
    }

}
